package com.cyam.controller;

import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.ContextLoader;

import com.octo.captcha.service.CaptchaService;
/**
 * 验证码Controller
 * @author CourageAQ
 *
 */
@Controller
public class JCaptchaController {
	
	private CaptchaService captchaService;

	@RequestMapping("jcaptcha")
	public void getImageJcaptcha(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		ApplicationContext context = ContextLoader.getCurrentWebApplicationContext();
		captchaService = (CaptchaService) context.getBean("captchaService");
		// Http 1.0 header
		response.setDateHeader("Expires", 1L);
		response.addHeader("Pragma", "no-cache");
		// Http 1.1 header
		response.setHeader("Cache-Control", "no-cache, no-store, max-age=0");
		response.setContentType("image/jpeg");

		ServletOutputStream out = response.getOutputStream();
		try {
			String captchaId = request.getSession(true).getId();
			BufferedImage challenge = (BufferedImage) captchaService
					.getChallengeForID(captchaId, request.getLocale());
			ImageIO.write(challenge, "jpg", out);
			out.flush();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			out.close();
		}
	}
	
	@RequestMapping("/validate")
	@ResponseBody
	public String validate(@RequestParam(value = "j_captcha", required = false) String j_captcha,
			HttpServletRequest request) {
		String string = "";
		Boolean isResponseCorrect = captchaService.validateResponseForID(
				request.getSession().getId(), j_captcha);
		if (!isResponseCorrect) {
			string = "fail";
		} else {
			string = "success";
		}
		return string;
	}
	
}
